﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace Clmp.WebForm
{
    public static class ControlBind<TEntity>
    {
        static Dictionary<string, PropertyInfo> PropertyDictionary = new Dictionary<string, PropertyInfo>();
        const int CutIndex = 3;

        static ControlBind()
        {
            Type entityType = typeof(TEntity);
            foreach (var a in entityType.GetProperties())
            {
                PropertyDictionary[a.Name] = a;
            }
        }

        public static void SetControlsValue(Panel panle, TEntity entity, params string[] filterProps)
        {
            foreach (Control control in panle.Controls)
            {
                if (control.ID == null || control.ID.Length <= CutIndex) continue;
                string key = control.ID.Substring(CutIndex);
                if (PropertyDictionary.ContainsKey(key))
                {
                    if (filterProps.Any(s => s == key)) continue;
                    object value = PropertyDictionary[key].GetValue(entity, null);
                    ControlMapping.SetControlValue(control, value);
                }
            }
        }

        public static void GetControlsValue(Panel panle, TEntity entity, params string[] filterProps)
        {
            foreach (Control control in panle.Controls)
            {
                if (control.ID == null || control.ID.Length <= CutIndex) continue;
                string key = control.ID.Substring(CutIndex);
                if (PropertyDictionary.ContainsKey(key))
                {
                    if (filterProps.Any(s => s == key)) continue;
                    if (ControlMapping.FilterGetControl(control))
                    {
                        var propInfo = PropertyDictionary[key];
                        object value = ControlMapping.GetControlValue(control, propInfo.PropertyType);
                        propInfo.SetValue(entity, value, null);
                    }
                }
            }
        }
    }
}
